import { onMounted, onBeforeUnmount, reactive, toRefs } from "vue"

function useMousePosition() {
    /* 定义响应式数据 */
    const state = reactive({
        x: 0,
        y: 0
    })

    /* mousemove事件监听器 */
    const mousemoveHandler = e => {
        // console.log(e.pageX, e.pageY);
        state.x = e.pageX
        state.y = e.pageY
    }

    /* 组件挂载完毕后 监听mousemove事件 */
    onMounted(
        () => {
            // 给body添加mousemove事件监听
            document.body.addEventListener(
                "mousemove",
                mousemoveHandler
            )
        }
    )

    /* 组件卸载前移除mousemove事件监听器 以避免内存泄漏 */
    onBeforeUnmount(
        () => {
            document.body.removeEventListener(
                "mousemove",
                mousemoveHandler
            )
            console.log("mousemoveHandler 已移除");
        }
    )

    /* 对模板暴露数据 */
    const { x, y } = toRefs(state)
    return {
        x, y
    }

}

export default useMousePosition